package com.coder.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.CarInfo;
import com.coder.rental.entity.Maintain;
import com.coder.rental.mapper.CarInfoMapper;
import com.coder.rental.mapper.MaintainMapper;
import com.coder.rental.service.IMaintainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 车辆保养 服务实现类
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@Service
public class MaintainServiceImpl extends ServiceImpl<MaintainMapper, Maintain> implements IMaintainService {

    @Resource
    private CarInfoMapper carInfoMapper;
    @Override
    public Page<Maintain> searchByPage(Page<Maintain> page, Maintain maintain) {
        QueryWrapper<Maintain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(maintain.getAutoNum()),
                "auto_num", maintain.getAutoNum());
        queryWrapper.eq(ObjectUtil.isNotEmpty(maintain.getItem()),
                "item", maintain.getItem());
        queryWrapper.eq(ObjectUtil.isNotEmpty(maintain.getLocation()),
                "location", maintain.getLocation());
        queryWrapper.ge(ObjectUtil.isNotEmpty(maintain.getLowMaintainTime()),
                "maintain_time", maintain.getLowMaintainTime());
        queryWrapper.le(ObjectUtil.isNotEmpty(maintain.getHighMaintainTime()),
                "maintain_time", maintain.getHighMaintainTime());
        queryWrapper.ge(ObjectUtil.isNotEmpty(maintain.getLowCost()),
                "cost", maintain.getLowCost());
        queryWrapper.le(ObjectUtil.isNotEmpty(maintain.getHighCost()),
                "cost", maintain.getHighCost());
        queryWrapper.orderByAsc("maintain_time");
        return baseMapper.selectPage(page, queryWrapper);


    }

    @Override
    public boolean delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
        if (!list.isEmpty()) {
            for (Integer id : list) {
                // 实保次数-1
                Maintain maintain = baseMapper.selectById(id);
                if(ObjectUtil.isNotEmpty(maintain)) {
                    Integer autoId = maintain.getAutoId();
                    CarInfo carInfo = carInfoMapper.selectById(autoId);
                    carInfo.setActualNum(carInfo.getActualNum() - 1);
                    carInfoMapper.updateById(carInfo);
                }
            }
            return baseMapper.deleteBatchIds(list) > 0;
        }
        return false;
    }
}
